//
//  UIImage+Extension.swift
//  zhengwutong
//
//  Created by wangshuguan on 16/9/5.
//  Copyright © 2016年 wangshuguan. All rights reserved.
//

import UIKit
extension UIImage {
    func cameraToNormal() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.size, true, UIScreen.main.scale)
        self.draw(at: CGPoint.zero)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }
    func photoToNormal() -> UIImage {
        // No-op if the orientation is already correct

        if (self.imageOrientation == .up){
            return self
        }
        var transform = CGAffineTransform.identity;
        switch (self.imageOrientation) {
        case .down,.downMirrored:
            transform = transform.translatedBy(x: self.size.width, y: self.size.height)
            transform = transform.rotated(by: CGFloat.pi)
            break
        case .left,.leftMirrored:
            transform = transform.translatedBy(x: self.size.width, y: 0)
            transform = transform.rotated(by: CGFloat.pi/2.0)
            break
        case .right,.rightMirrored:
            transform = transform.translatedBy(x: 0, y: self.size.height)
            transform = transform.rotated(by: -CGFloat.pi/2.0);
            break
        default:
            break
        }
        guard let _cgImage = self.cgImage else {
            return self
        }
        let bitsPerComponent:Int = _cgImage.bitsPerComponent
        let bytesPerRow:Int = _cgImage.bytesPerRow
        guard let colorSpace:CGColorSpace = _cgImage.colorSpace else{
            return self
        }
        let bitmapInfo:UInt32 = _cgImage.bitmapInfo.rawValue
        let w:Int = Int(size.width)
        let h:Int = Int(size.height)
        guard let ctx:CGContext = CGContext(data: nil, width: w, height: h, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else{
            return self
        }

        ctx.concatenate(transform);

        switch (self.imageOrientation) {
        
        case .left,.leftMirrored,.right,.rightMirrored:
            ctx.draw(_cgImage, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
            break
        default:
            ctx.draw(_cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
            break

        }
        guard let cgimg = ctx.makeImage() else{
            return self
        }
        return UIImage(cgImage: cgimg)
    }
    func base64String() -> String! {
        if let base64 = self.pngData()?.base64EncodedString(options: []){
            return base64
        }
        return ""
    }
    func jpegBase64String() -> String! {
        if let base64 = self.jpegData(compressionQuality: 1)?.base64EncodedString(options: []){
            return base64
        }
        return ""
    }
    func scaleToFitSize(_ maxWidth:CGFloat=1000.0,_ maxHeight:CGFloat=1000.0) -> UIImage {
        var size1 = self.size
        let maxWidth:CGFloat = maxWidth
        let maxHeight:CGFloat = maxHeight
        var newWidth:CGFloat = 0
        var newHeight:CGFloat = 0
        let radio = self.size.width/self.size.height
        if self.size.width > maxWidth ||  self.size.height > maxHeight{
            if radio>1 {
                newWidth = maxWidth
                newHeight = newWidth/radio
            }else{
                newHeight = maxHeight
                newWidth = newHeight*radio
            }
            size1 = CGSize(width: newWidth, height: newHeight)
        }
        
        UIGraphicsBeginImageContext(size1)
        let context = UIGraphicsGetCurrentContext()
        context?.translateBy(x: 0.0, y: size1.height)
        context?.scaleBy(x: 1.0, y: -1.0)
        context?.draw(self.cgImage!, in: CGRect(x: 0.0, y: 0.0, width: size1.width, height: size1.height))
        let scaledImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return scaledImage;
    }
    var reserveColor:UIColor {
        //获取图片信息
        let imgWidth:Int = Int(self.size.width) / 2
        let imgHeight:Int = Int(self.size.height) / 2
        //位图的大小＝图片宽＊图片高＊图片中每点包含的信息量
        let bitmapByteCount = imgWidth * imgHeight * 4
        //使用系统的颜色空间
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        //根据位图大小，申请内存空间
        let bitmapData = malloc(bitmapByteCount)
        defer {free(bitmapData)}
        //创建一个位图
        let context = CGContext(data: bitmapData,width: imgWidth,height: imgHeight,bitsPerComponent:8,bytesPerRow: imgWidth * 4,space: colorSpace,bitmapInfo:CGImageAlphaInfo.premultipliedLast.rawValue)
        //图片的rect
        let rect = CGRect(x:0, y:0, width:CGFloat(imgWidth), height:CGFloat(imgHeight))
        //将图片画到位图中
        context?.draw(self.cgImage!, in: rect)
        //获取位图数据
        let bitData = context?.data
        let data = unsafeBitCast(bitData, to:UnsafePointer<CUnsignedChar>.self)
        let cls = NSCountedSet.init(capacity: imgWidth * imgHeight)
        for x in 0..<imgWidth {
            for y in 0..<imgHeight {
                let offSet = (y * imgWidth + x) * 4
                let r = (data + offSet).pointee
                let g = (data + offSet+1).pointee
                let b = (data + offSet+2).pointee
                let a = (data + offSet+3).pointee
                if a > 0 {
                    //去除透明
                    if !(r == 255 && g == 255 && b == 255) {
                        //去除白色
                        cls.add([CGFloat(r),CGFloat(g),CGFloat(b),CGFloat(a)])
                    }
                }
            }
        }
        //找到出现次数最多的颜色
        let enumerator = cls.objectEnumerator()
        var maxColor:Array<CGFloat>? = nil
        var maxCount = 0
        while let curColor = enumerator.nextObject() {
            let tmpCount = cls.count(for: curColor)
            if tmpCount >= maxCount{
                maxCount = tmpCount
                maxColor = curColor as?Array<CGFloat>
            }
        }
        return UIColor.init(red: 1-(maxColor![0] / 255), green: 1-(maxColor![1] / 255), blue: 1-(maxColor![2] / 255), alpha: 1)
    }
    func saveToPhotosAlbum() {
        UIImageWriteToSavedPhotosAlbum(self, self, #selector(self.image(_:didFinishSavingWithErrorerror:contextInfo:)), nil)
    }
    @objc fileprivate func image(_ image: UIImage, didFinishSavingWithErrorerror:NSError?,contextInfo:AnyObject) {
        if let error = didFinishSavingWithErrorerror {
            UIAlertController.alertMessage(error.localizedDescription,title: "请在iPhone的\"设置-隐私-照片\"选项中，允许\(Config.App.displayName)访问你的手机照片")
        }else{
            UIAlertController.alertMessage("保存成功")
        }
    }
    func toBlurLevel(_ level:Float) -> UIImage {
        guard let cgImage = self.cgImage else{
            return self
        }
        let context = CIContext(options: nil)
        let ciImage = CIImage(cgImage: cgImage)
        let filter = CIFilter(name: "CIGaussianBlur")
        filter?.setValue(ciImage, forKey: kCIInputImageKey)
        filter?.setValue(NSNumber(value : level), forKey: kCIInputRadiusKey)
        guard let result = filter?.value(forKey: kCIOutputImageKey) as? CIImage,let outImage = context.createCGImage(result, from: ciImage.extent) else { return self }
        return UIImage(cgImage: outImage)
    }
}
